//
//  IGSearchVC.m
//  jingdongfang
//
//  Created by BOE on 2017/8/28.
//  Copyright © 2017年 LJL. All rights reserved.
//

#import "IGSearchVC.h"
#import "SliderViewController.h"
#import "IGArtistVC.h"
#import "IGArticleVC.h"
#import "IGSearchHotKeyCell.h"
#import "IGCollectionHeaderView.h"
#import "IGStoreVC.h"
#import "DWQTagView.h"
#import "HistorySearchCell.h"
#import "HotSerachCell.h"
#import "IGSearchHisManager.h"

static NSString *const HotCellID = @"HotCellID";
static NSString *const HistoryCellID = @"HistoryCellID";
@interface IGSearchVC ()<SliderViewControllerDelegate, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource,DWQTagViewDelegate>

@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) SliderViewController *sliderVC;
@property (nonatomic, strong) IGProductVC *artVC;
@property (nonatomic, strong) IGArtistVC *artistVC;
@property (nonatomic, strong) IGArticleVC *articleVC;
@property (nonatomic, assign) NSInteger index;
@property (nonatomic, copy) NSString *searchKey;

@property (nonatomic, strong) UITableView *tableview;
/** 历史搜索数组 */
@property (nonatomic, strong) NSMutableArray *historyArr;
/** 热门搜索数组 */
@property (nonatomic, strong) NSMutableArray *hotArray;
/** 得到热门搜索TagView的高度 */
@property (nonatomic ,assign) CGFloat tagViewHeight;
@end

@implementation IGSearchVC

- (instancetype)initWithSearchKey:(NSString *)searchKey {
    self = [super init];
    if (self) {
        _searchKey = searchKey;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor mainBackgroundColor];
    if ([self.defaulSel isEqualToString:@"1"]) {
        _index=1;
    }
    _index = 0;
    [self initNavBar];
    [self initData];
    [self createUI];
    [self loadSearchHotKey];
    if (self.searchKey) {
        _searchBar.text = _searchKey;
        [self searchBarSearchButtonClicked:_searchBar];
    }
}

///>获取搜索历史
- (void)initData{
    self.historyArr = [NSMutableArray arrayWithArray:[[IGSearchHisManager shareManager] getHisArray]];
}

- (void)createUI {
     [self.view addSubview:self.tableview];
    
    //商品搜索不显示sliderVC
    if (self.type == IGHotKeyTypeStore) {
        return;
    }
    
    [self.view addSubview:self.sliderVC];
    [self.sliderVC buildUI];
    [_sliderVC selectIndex:[self.defaulSel integerValue]];
}

- (void)setIndex:(NSInteger)index {
    if (_index != index) {
        _index = index;
    }
    if (_sliderVC) {
        [_sliderVC selectIndex:index];
        [self loadData];
    }
}

- (void)initNavBar {
    UIView *leftBarView = [[UIView alloc]initWithFrame:CGRectMake(0, 20, 5, 44)];
    UIBarButtonItem *leftBtnItem = [[UIBarButtonItem alloc]initWithCustomView:leftBarView];
    UIBarButtonItem *leftSpaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    leftSpaceItem.width = -15;
    
    self.navigationItem.leftBarButtonItems = @[leftSpaceItem, leftBtnItem];

    if (@available(iOS 11, *)) {
        UIView *searchbg = [[UIView alloc]init];
        searchbg.backgroundColor = [UIColor clearColor];
        self.navigationItem.titleView = searchbg;
        [searchbg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(44);
            make.width.mas_equalTo(KSCREENWIDTH - 90);
        }];
        _searchBar = [[UISearchBar alloc] init];
        _searchBar.searchBarStyle = UISearchBarStyleMinimal;
        _searchBar.delegate = self;
        [searchbg addSubview:_searchBar];
        [self.searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(searchbg).with.offset(7.0);
            make.left.equalTo(searchbg).with.offset(0);
            make.right.equalTo(searchbg).with.offset(-10);
            make.bottom.equalTo(searchbg).with.offset(-7.0);
        }];
    } else {
        _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 44)];
        _searchBar.searchBarStyle = UISearchBarStyleMinimal;
        _searchBar.delegate = self;
        self.navigationItem.titleView = _searchBar;
    }
    
    _searchBar.placeholder = (self.type == IGHotKeyTypeStore?NSLocalizedString(@"Search for Items", nil):NSLocalizedString(@"What are you looking for?", nil));
    UITextField * searchField = [_searchBar valueForKey:@"_searchField"];
    [searchField setValue:[UIFont systemFontOfSize:12] forKeyPath:@"_placeholderLabel.font"];
    
    [self ig_setupRightButtonItemWithTitle:NSLocalizedString(@"Cancel", nil) image:nil highLightedImage:nil];

}

- (void)ig_rightButtonPressed:(id)sender {
    [self.searchBar resignFirstResponder];
    
    [self.navigationController popViewControllerAnimated:NO];
}


- (SliderViewController *)sliderVC {
    if (!_sliderVC) {
        _sliderVC = [[SliderViewController alloc] initWithFrame:CGRectMake(0, NavigationMagin, KSCREENWIDTH, KSCREENHEIGHT - NavigationMagin)];
        _sliderVC.hidden = YES;
        _sliderVC.slideSwitchViewDelegate = self;
        _sliderVC.shadowImageView.backgroundColor = [UIColor clearColor];
        _sliderVC.topScrollView.backgroundColor = [UIColor c3Color];
        _sliderVC.tabItemNormalColor = RGB(115, 115, 115);
        _sliderVC.tabItemSelectedColor =[UIColor blackColor];
    }
    return _sliderVC;
}

#pragma mark - NetWork
- (void)loadSearchHotKey {
    __weak typeof(self) weakSelf = self;
    IGHotKeyApi *hotKeyApi = [IGHotKeyApi new];
    if (self.type == IGHotKeyTypeStore) {
        hotKeyApi.type = IGHotKeyTypeStore;
    } else {
        hotKeyApi.type = IGHotKeyTypeProduct;
    }
    [hotKeyApi startWithDecodeClass:[IGHotKeyResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            IGHotKeyResp *resp = responseObject;
            weakSelf.hotArray = [NSMutableArray arrayWithArray:resp.data.lstTags];
            [weakSelf.tableview reloadData];
        }
    }];
}

#pragma mark --<SliderViewControllerDelegate>

- (NSUInteger)numberOfTab:(SliderViewController *)view {
    return 3;
}

- (UIViewController *)slideSwitchView:(SliderViewController *)view viewOfTab:(NSUInteger)number {
    __weak typeof(self) weakSelf = self;
    if (number == 0) {
        _artVC = [[IGProductVC alloc] init];
        _artVC.title = NSLocalizedString(@"Artworks", nil);
        if (self.search4PubBlock) {
            _artVC.search4PubBlock = ^(IGArtWorkModel *dataBase) {
                weakSelf.search4PubBlock(dataBase);
                [weakSelf.navigationController popViewControllerAnimated:YES];
            };
        }
        _artVC.searchKey = self.searchKey;
        return _artVC;
    } else if (number == 1) {
        _artistVC = [[IGArtistVC alloc] init];
        _artistVC.title = NSLocalizedString(@"User", nil);
        _artistVC.searchKey = self.searchKey;
        return _artistVC;
    } else if (number == 2) {
        _articleVC = [[IGArticleVC alloc] init];
        _articleVC.title = NSLocalizedString(@"Articles", nil);
        _articleVC.searchKey = self.searchKey;
        return _articleVC;
    }
    return nil;
}

- (void)slideSwitchView:(SliderViewController *)view didselectTab:(NSUInteger)number {
    _index = number;
    [self.searchBar resignFirstResponder];
    [self loadData];
}

#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    self.searchKey = searchBar.text;
    [[IGSearchHisManager shareManager] addSearchKey:self.searchKey];
    [self loadData];
    if (self.type == IGHotKeyTypeStore) {
        return;
    }
    _sliderVC.hidden = NO;
}

- (void)loadData {
    if (self.type == IGHotKeyTypeStore) {
        IGStoreVC *storeVC = [[IGStoreVC alloc] init];
        storeVC.searchKey = self.searchKey;
        [UIViewController ig_pushViewController:storeVC animated:YES];
        return;
    } else {
        if (_index == 0) {
            _artVC.searchKey = self.searchKey;
        } else if (_index == 1) {
            _artistVC.searchKey = self.searchKey;
        } else if (_index == 2) {
            _articleVC.searchKey = self.searchKey;
        }
    }
}

#pragma mark --
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (self.historyArr.count == 0) {
        return 1;
    }
    else
    {
        if (section == 0) {
            return 1;
        }
        else
        {
            return self.historyArr.count;
        }
    }
}
/** section的数量 */
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.historyArr.count == 0) {
        return 1;
    }
    else
    {
        return 2;
    }
}
/** 使第一个cell（热门搜索的cell不可编辑） */
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return UITableViewCellEditingStyleNone;
    }
    else
    {
        return UITableViewCellEditingStyleDelete;
    }
}
/** CELL */
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.historyArr.count == 0) {
        HotSerachCell *hotCell = [tableView dequeueReusableCellWithIdentifier:HotCellID forIndexPath:indexPath];
        
        hotCell.selectionStyle = UITableViewCellSelectionStyleNone;
        hotCell.userInteractionEnabled = YES;
        hotCell.hotSearchArr = self.hotArray;
        hotCell.dwqTagV.delegate = self;
        /** 将通过数组计算出的tagV的高度存储 */
        self.tagViewHeight = hotCell.dwqTagV.frame.size.height;
        return hotCell;
    }
    else
    {
        if (indexPath.section == 0) {
            HotSerachCell *hotCell = [tableView dequeueReusableCellWithIdentifier:HotCellID forIndexPath:indexPath];
            hotCell.dwqTagV.delegate = self;
            hotCell.selectionStyle = UITableViewCellSelectionStyleNone;
            hotCell.userInteractionEnabled = YES;
            hotCell.hotSearchArr = self.hotArray;
            /** 将通过数组计算出的tagV的高度存储 */
            self.tagViewHeight = hotCell.dwqTagV.frame.size.height;
            return hotCell;
        }
        else
        {
            HistorySearchCell *historyCell = [tableView dequeueReusableCellWithIdentifier:HistoryCellID forIndexPath:indexPath];
            historyCell.selectionStyle = UITableViewCellSelectionStyleNone;
            historyCell.backgroundColor = [UIColor mainBackgroundColor];
            historyCell.tagNameLab.text = self.historyArr[indexPath.row];
            historyCell.tagNameLab.userInteractionEnabled = YES;
            __weak typeof(self) weakSelf = self;
            [historyCell.tagNameLab setTapActionWithBlock:^{
                NSString *keyWord = weakSelf.historyArr[indexPath.row];
                weakSelf.searchBar.text = keyWord;
                [weakSelf searchBarSearchButtonClicked:weakSelf.searchBar];
            }];
            [historyCell.removeTagBtn addTarget:self action:@selector(removeSingleTagClick:) forControlEvents:UIControlEventTouchUpInside];
            historyCell.removeTagBtn.tag = 250 + indexPath.row;
            
            return historyCell;
        }
    }
}
/** HeaderView */
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 45)];
    headView.backgroundColor = [UIColor mainBackgroundColor];
    for (UILabel *lab in headView.subviews) {
        [lab removeFromSuperview];
    }
    UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, KSCREENWIDTH/2, 45)];
    titleLab.textColor = [UIColor c5Color];
    titleLab.font = [UIFont font14];
    [headView addSubview:titleLab];
    if (self.historyArr.count == 0) {
        titleLab.text = @"热门搜索";
    } else {
        if (section == 0) {
            titleLab.text = @"热门搜索";
        } else {
            titleLab.text = @"搜索历史";
            UILabel *removeAllHistory = [UILabel new];
            removeAllHistory.frame = CGRectMake(KSCREENWIDTH/2, 0, KSCREENWIDTH/2-15, 46);
            removeAllHistory.backgroundColor = [UIColor mainBackgroundColor];
            removeAllHistory.textAlignment = NSTextAlignmentRight;
            removeAllHistory.textColor = [UIColor c5Color];
            removeAllHistory.text = @"清除历史";
            removeAllHistory.font = [UIFont font14];
            removeAllHistory.userInteractionEnabled = YES;
            __weak typeof(self) weakSelf = self;
            [removeAllHistory setTapActionWithBlock:^{
                [weakSelf removeAllHistoryBtnClick];
            }];
            [headView addSubview:removeAllHistory];
        }
    }
    return headView;
}

/** 头部的高 */
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 45;
}
/** cell的高 */
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.historyArr.count == 0) {
        
        return self.tagViewHeight + 40;
    }
    else
    {
        if (indexPath.section == 0) {
            return self.tagViewHeight + 40;
        }
        else
        {
            return 46;
        }
    }
}
/** FooterView的高 */
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

#pragma mark -- 实现点击热门搜索tag  Delegate
-(void)DWQTagView:(UIView *)dwq fetchWordToTextFiled:(NSString *)KeyWord
{
    self.searchBar.text = KeyWord;
    [self searchBarSearchButtonClicked:_searchBar];
}

#pragma mark -- 删除单个搜索历史
-(void)removeSingleTagClick:(UIButton *)removeBtn
{
    [self.historyArr removeObjectAtIndex:removeBtn.tag - 250];
    [IGSearchHisManager shareManager].hisArray = self.historyArr;
    [self.tableview reloadData];
}
#pragma mark -- 删除所有的历史记录
-(void)removeAllHistoryBtnClick
{
    [self.historyArr removeAllObjects];
    [IGSearchHisManager shareManager].hisArray = self.historyArr;
    [self.tableview reloadData];
}

#pragma mark -- 懒加载
-(UITableView *)tableview
{
    if (!_tableview) {
        self.automaticallyAdjustsScrollViewInsets = NO;
        _tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) style:UITableViewStylePlain];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableview registerClass:[HotSerachCell class] forCellReuseIdentifier:HotCellID];
        [_tableview registerNib:[UINib nibWithNibName:@"HistorySearchCell" bundle:nil] forCellReuseIdentifier:HistoryCellID];
        _tableview.backgroundColor = [UIColor mainBackgroundColor];
    }
    return _tableview;
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
